package utils

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"log"
	"strings"
)

type Mysql struct {
	Address  string  `yaml:"addr"`
	Username string  `yaml:"uid"`
	Password string  `yaml:"pwd"`
	Database string  `yaml:"db"`
	Instance *sql.DB `yaml:"-"`
}

func deleteEmpty(s []string) []string {
	var slice []string
	for _, str := range s {
		str = strings.Trim(str, " \r\n\v\t")
		if str != "" {
			slice = append(slice, str)
		}
	}
	return slice
}

func (that *Mysql) Open() (err error) {
	uri := fmt.Sprintf("%s:%s@tcp(%s)/%s", that.Username, that.Password, that.Address, that.Database)
	if that.Instance, err = sql.Open("mysql", uri); err != nil {
		return err
	}
	return that.Instance.Ping()
}

func (that *Mysql) Close() (err error) {
	if that.Instance != nil {
		err = that.Instance.Close()
	}
	return err
}

func (that *Mysql) Closed(serverType string) error {
	that.Instance.Begin()

	query := fmt.Sprintf("SELECT snoring_types FROM game_snoring WHERE id=1;")
	rows, err := that.Instance.Query(query)
	log.Println(query)
	if err != nil {
		return err
	}

	var str string
	if rows.Next() {
		if err = rows.Scan(&str); err != nil {
			return err
		}
	}

	log.Println("已关闭游戏类型列表:", str)

	err = rows.Close()
	if err != nil {
		return err
	}

	snoringTypes := strings.Split(str, ",")
	snoringTypes = deleteEmpty(snoringTypes)

	for _, v := range snoringTypes {
		if v == serverType {
			return nil
		}
	}

	snoringTypes = append(snoringTypes, serverType)
	str = strings.Join(snoringTypes, ",")

	insert := fmt.Sprintf("UPDATE game_snoring SET snoring_types='%s' WHERE id=1;", str)
	err = that.Instance.QueryRow(insert).Err()
	log.Println(insert)

	return err
}

func (that *Mysql) Opened(serverType string) error {
	query := fmt.Sprintf("SELECT snoring_types FROM game_snoring WHERE id=1;")
	rows, err := that.Instance.Query(query)
	log.Println(query)
	if err != nil {
		return err
	}

	var str string
	if rows.Next() {
		if err = rows.Scan(&str); err != nil {
			return err
		}
	}

	log.Println("已开启游戏类型列表:", str)

	err = rows.Close()
	if err != nil {
		return err
	}

	snoringTypes := strings.Split(str, ",")
	snoringTypes = deleteEmpty(snoringTypes)

	isOpened := true
	for i, v := range snoringTypes {
		if v == serverType {
			isOpened = false
			snoringTypes[i] = ""
			break
		}
	}
	if isOpened {
		return nil
	}

	snoringTypes = deleteEmpty(snoringTypes)
	str = strings.Join(snoringTypes, ",")

	insert := fmt.Sprintf("UPDATE game_snoring SET snoring_types='%s' WHERE id=1;", str)
	err = that.Instance.QueryRow(insert).Err()
	log.Println(insert)

	return err
}
